package com.msb.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.mall.common.utils.PageUtils;
import com.msb.mall.common.utils.Query;

import com.msb.mall.product.dao.CategoryDao;
import com.msb.mall.product.entity.CategoryEntity;
import com.msb.mall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> queryWithTree(Map<String, Object> params) {
        //查询所有商品分类
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);

        //拆解为树状结构

        Map<Long, List<CategoryEntity>> parentListMap = categoryEntityList.stream()
                .collect(Collectors.groupingBy(CategoryEntity::getParentCid));

        return categoryEntityList.stream()
                .filter(category -> category.getParentCid() != null && category.getParentCid() == 0)
                .map(category -> this.queryChildren(category, parentListMap))
                .sorted(Comparator.comparingInt(obj -> (obj.getSort() == null ? 0 : obj.getSort())))
                .collect(Collectors.toList());
    }

    private CategoryEntity queryChildren(CategoryEntity category, Map<Long, List<CategoryEntity>> parentListMap) {
        Long catId = category.getCatId();
        List<CategoryEntity> childrenList = parentListMap.get(catId);
        if (childrenList != null && !childrenList.isEmpty()) {
            childrenList = childrenList.stream()
                    .map(children -> this.queryChildren(children, parentListMap))
                    .collect(Collectors.toList());
        }
        category.setChildrenList(childrenList);
        return category;
    }

}